﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace OpenPhotoAlbum.Controls
{
    public class CaptchaDataServices
    {
        private static readonly CaptchaDataServices instance = new CaptchaDataServices();

        static CaptchaDataServices() { }

        public static CaptchaDataServices Instance
        {
            get { return instance; }
        }

        private const string KEY = "FGTFHT12";

        private Random _rn;
        private DES _des;
        private ICryptoTransform _encryptor;
        private ICryptoTransform _decryptor;

        private CaptchaDataServices()
        {
            _rn = new Random();

            _des = new DESCryptoServiceProvider();
            _des.Mode = CipherMode.ECB;
            _des.Key = Encoding.ASCII.GetBytes(KEY);

            _encryptor = _des.CreateEncryptor();
            _decryptor = _des.CreateDecryptor();
        }

        public int GenerateRandomNumber()
        {
            if (_rn == null) { _rn = new Random(); }

            return _rn.Next(1, 10000);
        }

        public string Encrypt(int number)
        {
            byte[] byteArray = BitConverter.GetBytes(number);
            byte[] encryptedByteArray = _encryptor.TransformFinalBlock(byteArray, 0, byteArray.Length);
            return Convert.ToBase64String(encryptedByteArray);
        }

        public int Decrypt(string encryptedBase64String)
        {
            byte[] encryptedByteArray = Convert.FromBase64String(encryptedBase64String);
            byte[] byteArray = _decryptor.TransformFinalBlock(encryptedByteArray, 0, encryptedByteArray.Length);
            return BitConverter.ToInt32(byteArray, 0);
        }
    }
}
